package com.xyh.ollama_test.service;

import com.xyh.ollama_test.enums.Department;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PermissionService {
    // 使用final修饰，确保线程安全
    private final Map<String, Department> userDepartments;
    private final Map<Department, Set<Department>> departmentAccess;

    public PermissionService() {
        this.userDepartments = Map.of(
                "user1", Department.HR,
                "user2", Department.FINANCE,
                "user3", Department.TECH,
                "user4",Department.SALES,
                "user5",Department.SALES,
                "admin", Department.ADMIN
        );

        // 初始化部门访问权限
        this.departmentAccess = new EnumMap<>(Department.class);
        departmentAccess.put(Department.HR, Set.of(Department.HR, Department.ADMIN));
        departmentAccess.put(Department.FINANCE, Set.of(Department.FINANCE, Department.ADMIN));
        departmentAccess.put(Department.TECH, Set.of(Department.TECH, Department.ADMIN));
        departmentAccess.put(Department.SALES, Set.of(Department.SALES, Department.ADMIN));
        departmentAccess.put(Department.ADMIN, EnumSet.allOf(Department.class));
    }

    public boolean hasPermission(String userId, Department dataDepartment) {
        if (userId == null || dataDepartment == null) {
            return false;
        }

        Department userDept = getUserDepartment(userId);
        if (userDept == null || userDept == Department.UNKNOWN) {
            return false;
        }

        // 管理员有所有权限
        if (userDept == Department.ADMIN) {
            return true;
        }

        // 检查用户部门是否有权限访问数据部门
        Set<Department> accessibleDepartments = departmentAccess.get(userDept);
        return accessibleDepartments != null && accessibleDepartments.contains(dataDepartment);
    }


    public Department getUserDepartment(String userId) {
        if (userId == null) {
            return Department.UNKNOWN;
        }
        return userDepartments.getOrDefault(userId, Department.UNKNOWN);
    }


    public String getUserDepartmentName(String userId) {
        return getUserDepartment(userId).getName();
    }
}